package model;

import java.io.IOException;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class User {
	private String uid;
	private String first_name;
	private String last_name;
	private String email;
	private String pass;
	private String website;
	private String yahoo;
	private String bio;
	private String avatar;
	private String user_level;
	private String active;
	private String userName;
	private Date registration_date;
	int length;
	int maxLength;

	public User(String userName, String pass) {
		this.userName = userName;
		this.pass = pass;
	}
	public User() {
	};
	public User(String uid, String first_name, String last_name,
			String user_name, String email, String pass, String website,
			String yahoo, String bio, String avatar, String user_level,
			String active, Date registration_date) {
		this.uid = uid;
		this.first_name = first_name;
		this.last_name = last_name;
		this.userName = user_name;
		this.email = email;
		this.pass = pass;
		this.website = website;
		this.yahoo = yahoo;
		this.bio = bio;
		this.avatar = avatar;
		this.user_level = user_level;
		this.active = active;
		this.registration_date = registration_date;
		this.maxLength = 40;
		this.length = 2;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getUid() {
		return uid;
	}
	public void setUid(String uid) {
		this.uid = uid;
	}
	public String getFirst_name() {
		return first_name;
	}
	public void setFirst_name(String first_name) {
		this.first_name = first_name;
	}
	public String getLast_name() {
		return last_name;
	}
	public void setLast_name(String last_name) {
		this.last_name = last_name;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getPass() {
		return pass;
	}
	public void setPass(String pass) {
		this.pass = pass;
	}
	public String getWebsite() {
		return website;
	}
	public void setWebsite(String website) {
		this.website = website;
	}
	public String getYahoo() {
		return yahoo;
	}
	public void setYahoo(String yahoo) {
		this.yahoo = yahoo;
	}
	public String getBio() {
		return bio;
	}
	public void setBio(String bio) {
		this.bio = bio;
	}
	public String getAvatar() {
		return avatar;
	}
	public void setAvatar(String avatar) {
		this.avatar = avatar;
	}
	public String getUser_level() {
		return user_level;
	}
	public void setUser_level(String user_level) {
		this.user_level = user_level;
	}
	public String getActive() {
		return active;
	}
	public void setActive(String active) {
		this.active = active;
	}
	public Date getRegistration_date() {
		return registration_date;
	}
	public void setRegistration_date(Date registration_date) {
		this.registration_date = registration_date;
	}
	public boolean isUID(String uid) throws IOException{ /*kiem tra tinh hop le cua nid va co nam trong DB hay khong*/
		if(uid==null) return false;
		if(uid.trim().equals(""))return false;
		uid.trim();
		int id = -1;
		try {
			id = Integer.parseInt(uid);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		PreparedStatement sqlp = null;
		Connection connection = new ConnectDB().getConnection();
		try {
			sqlp = connection.prepareStatement("SELECT uid FROM users where uid = ? ");
			sqlp.setInt(1, id);
			ResultSet rs = sqlp.executeQuery();
			while (rs.next() == true) {
				return true;
			}
			sqlp.close();
			connection.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	public boolean chexUser() {
		boolean result = true;
		if ((this.checkEmail() != "") || (this.checkFirstName() != "")
				|| (this.checkLastName()) != "" || (this.checkUserName() != ""))
			return false;
		return result;
	}
	public String checkFirstName() {
		String result = "", i = this.first_name;
		if (i == null) {
			return "Bạn chưa nhập First Name.";
		} else {
			i = i.trim();
			if (i == "") {
				return "Bạn chưa nhập First Name.";
			} else if (i.length() < length) {
				return "First Name phải nhiều hơn " + length + " ký tự";
			} else if (i.length() > maxLength) {
				return "First Name phải ít hơn " + maxLength + " ký tự";
			}
		}
		return result;
	}
	public String checkLastName() {
		String result = "", i = this.last_name;
		if (i == null) {
			return "Bạn chưa nhập Last Name.";
		} else {
			i = i.trim();
			if (i == "") {
				return "Bạn chưa nhập Last Name.";
			} else if (i.length() < length) {
				return "Last Name phải nhiều hơn " + length + " ký tự";
			} else if (i.length() > maxLength) {
				return "Last Name phải ít hơn " + maxLength + " ký tự";
			}
		}
		return result;
	}
	public String checkUserName() {
		String result = "", i = this.userName;
		if (i == null) {
			return "Bạn chưa nhập User Name.";
		} else {
			i = i.trim();
			if (i == "") {
				return "Bạn chưa nhập User Name.";
			} else if (i.length() < length) {
				return "User Name phải nhiều hơn " + length + " ký tự";
			} else if (i.length() > maxLength) {
				return "User Name phải ít hơn " + maxLength + " ký tự";
			} else {
				PreparedStatement sqlu = null;
				Connection con = new ConnectDB().getConnection();
				try {
					sqlu = con
							.prepareStatement("select user_name from users where user_name = ? ");
					sqlu.setString(1, userName);
					ResultSet rs = sqlu.executeQuery();
					while (rs.next()) {
						return "Tên User đã tồn tại.";
					}
					sqlu.close();
					con.close();
					
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
		return result;
	}

	public int getSizeDB() {
		int result = 0;
		PreparedStatement sqlu = null;
		Connection con = new ConnectDB().getConnection();
		try {
			sqlu = con.prepareStatement("select COUNT(uid) from users ");
			ResultSet rs = sqlu.executeQuery();
			while (rs.next()) {
				return rs.getInt(1);
			}
			sqlu.close();
			con.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return result;
	}

	public String checkEmail() {
		String email = this.email;
		String result = "";
		if (email == null) {
			return "Bạn chưa nhập email .";
		} else if (email.trim() == "") {
			return "Bạn chưa nhập email .";
		} else {
			Pattern patternObject = Pattern
					.compile("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");
			Matcher matcherObject = patternObject.matcher(email.trim());
			if (!matcherObject.matches())
				return "Địa chỉ email không hợp lệ";
			PreparedStatement sqlu = null;
			Connection con = new ConnectDB().getConnection();
			try {
				sqlu = con
						.prepareStatement("select * from users where email = ? ");
				sqlu.setString(1, email.trim());
				ResultSet rs = sqlu.executeQuery();
				while (rs.next()) {
					result = "Email đã tồn tại.";
				}
				sqlu.close();
				con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	public boolean checkIssetPass(String pass, String rpass) {
		if ((this.checkPass(pass) == "")
				&& (this.checkRePass(pass, rpass) == ""))
			return true;
		return false;
	}

	public String checkPass(String pass) {
		if (pass == null) {
			return "Bạn chưa nhập password.";
		} else {
			if (pass == "") {
				return "Bạn chưa nhập password.";
			} else if (pass.length() < 6) {
				return "Password phải có ít nhất 6 ký tự";
			}
		}
		return "";
	}

	public String checkRePass(String pass, String rpass) {
		String result = "";
		if (pass == null) {
			return "*";
		}
		if (rpass == null) {
			return "Bạn chưa nhập password.";
		} else {
			if (rpass.trim() == "") {
				return "Bạn chưa nhập password.";
			} else {
				pass = pass.trim();
				rpass = rpass.trim();
				if (!pass.equals(rpass)) {
					return "Nhập sai password.";
				}
			}
		}
		return result;
	}

	public int[] getUID(String orby) {
		String[] sort = { "first_name", "last_name", "user_name", "email",
				"pass", "website", "yahoo", "bio", "avatar", "user_level",
				"active", "registration_date" };
		if (orby == null) {
			orby = "user_name";
		} else {
			orby.trim();
			if (!this.indexOf(orby, sort)) {
				orby = "user_name";	
			}
		}
		int[] result = new int[this.getSizeDB()];
		int i = 0;
		PreparedStatement sqlu = null;
		Connection connection = new ConnectDB().getConnection();
		try {
			sqlu = connection
					.prepareStatement("SELECT uid FROM users ORDER BY " + orby
							+ " ASC");
			ResultSet rs = sqlu.executeQuery();
			while (rs.next() == true) {
				result[i] = rs.getInt(1);
				i++;
			}
			rs.close();
			sqlu.close();
			connection.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	public String getFullName(String userName, int s) {
		PreparedStatement sqlu = null;
		Connection con = new ConnectDB().getConnection();
		try {
			sqlu = con
					.prepareStatement("select first_name , last_name from users where user_name = ? ");
			sqlu.setString(1, userName);
			ResultSet rs = sqlu.executeQuery();
			while (rs.next()) {
				String fn = rs.getString(1);
				String ln = rs.getString(2);
				return (s != 1) ? (fn + " " + ln) : (ln + " " + fn);
			}
			rs.close();
			sqlu.close();
			con.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return "";
	}

	public boolean Register() {
		PreparedStatement sqlr = null;
		boolean result = false;
		Connection con = new ConnectDB().getConnection();
		try {
			sqlr = con
					.prepareStatement("INSERT INTO users(first_name, last_name, user_name, email, pass, user_level, active, registration_date) VALUES (?, ?, ?, ?, ?, ?, ?, NOW())");
			sqlr.setString(1, this.getFirst_name());
			sqlr.setString(2, this.getLast_name());
			sqlr.setString(3, this.getUserName());
			sqlr.setString(4, this.getEmail());
			sqlr.setString(5, this.getPass());
			sqlr.setInt(6, 1);
			sqlr.setString(7, this.active);
			int number = sqlr.executeUpdate();
			if (number > 0) {
				result = true;
			}
			sqlr.close();
			con.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return result;
	}
	public boolean del(int uid){
		PreparedStatement delpd = null;
		Connection con = new ConnectDB().getConnection();
		try {
			
			delpd = con.prepareStatement("DELETE FROM users WHERE uid = ? LIMIT 1");
			delpd.setInt(1, uid);
			int number = delpd.executeUpdate();
			if (number > 0) {
				return true;
			}
			delpd.close();
			con.close();
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
		return  false;
	}
	public String checkLogin() {
		PreparedStatement sqll = null;
		String result = "Tài khoản hoặc mật khẩu không đúng!";

		Connection c = new ConnectDB().getConnection();
		try {
			sqll = c.prepareStatement("select user_name , pass , active from users where user_name = ? AND pass = ?");
			sqll.setString(1, this.userName);
			sqll.setString(2, this.pass);
			ResultSet rs = sqll.executeQuery();

			while (rs.next() == true) {

				String at = rs.getString(3);
				if (at.equals("yes")) {
					return "";
				} else {
					return "Tài khoản chưa được kích hoạt.";
				}
			}
			sqll.close();
			c.close();
		} catch (SQLException e) {

			e.printStackTrace();
		}

		return result;
	}

	public User getUserByID(int userid) {
		PreparedStatement sqll = null;
		User result = null;
		Connection c = new ConnectDB().getConnection();
		try {
			sqll = c.prepareStatement("select * from users where uid = ?");
			sqll.setInt(1, userid);
			ResultSet rs = sqll.executeQuery();

			while (rs.next() == true) {
				String uid = String.valueOf(rs.getInt(1));
				String fn = rs.getString(2);
				String ln = rs.getString(3);
				String un = rs.getString(4);
				String e = rs.getString(5);
				String p = rs.getString(6);
				String w = rs.getString(7);
				String y = rs.getString(8);
				String b = rs.getString(9);
				String a = rs.getString(10);
				String l = String.valueOf(rs.getInt(11));
				String at = rs.getString(12);
				Date rd = rs.getDate(13);
				result = new User(uid, fn, ln, un, e, p, w, y, b, a, l, at, rd);
			}
			sqll.close();
			c.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}

		return result;
	}

	public User getUserByName(String UserName) {
		UserName = (UserName == null) ? this.getUserName() : UserName;
		PreparedStatement sqll = null;
		User result = null;

		Connection c = new ConnectDB().getConnection();
		try {
			sqll = c.prepareStatement("select * from users where user_name = ?");
			sqll.setString(1, UserName);
			ResultSet rs = sqll.executeQuery();

			while (rs.next() == true) {
				String uid = String.valueOf(rs.getInt(1));
				String fn = rs.getString(2);
				String ln = rs.getString(3);
				String un = rs.getString(4);
				String e = rs.getString(5);
				String p = rs.getString(6);
				String w = rs.getString(7);
				String y = rs.getString(8);
				String b = rs.getString(9);
				String a = rs.getString(10);
				String l = String.valueOf(rs.getInt(11));
				String at = rs.getString(12);
				Date rd = rs.getDate(13);
				result = new User(uid, fn, ln, un, e, p, w, y, b, a, l, at, rd);
			}
			sqll.close();
			c.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}

		return result;
	}

	public boolean isAdmin(String in) {
		boolean result = false;
		if (in == null) {
			return false;
		} else {
			int a = 0;
			try {
				a = Integer.parseInt(in);
				if (a == 4) {
					return true;
				}
			} catch (Exception e) {
				e.printStackTrace();
				System.out.println("khong parse duoc .");
			}
		}
		return result;
	}

	public boolean indexOf(String agr0, String[] content) {
		for (String i : content) {
			if (agr0.equals(i))
				return true;
		}
		return false;

	}

	public String toString() {
		return this.uid + " ;" + this.first_name + " ;" + this.userName + " ;"
				+ this.email + " ;" + this.pass + " ;" + this.website + " ;"
				+ this.yahoo + " ;" + this.bio + " ;" + this.avatar + " ;"
				+ this.user_level + " ;" + this.active + " ;"
				+ this.registration_date
		;
	}
	public boolean upDateLV(String uid,String lv) {
		if(lv==null)return false;
		if(lv.trim().equals(""))return false;
		int l = 0;
		int id =0;
		try {
			l=Integer.parseInt(lv);
			id = Integer.parseInt(uid);
		} catch (Exception e) {
			return false;
		}
		PreparedStatement sqlr = null;
		Connection con = new ConnectDB().getConnection();
		try {
			sqlr = con.prepareStatement("UPDATE users SET user_level = ? WHERE uid = ? LIMIT 1");
			sqlr.setInt(1, l);
			sqlr.setInt(2, id);
			int number = sqlr.executeUpdate();
			if (number > 0) {
				return true;
			}
			sqlr.close();
			con.close();
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
		return false;
	}
}
